<?php

namespace App\Library\Logic;

use App\Library\Requests\Auction\AuctionOrderPageRequest;
use App\Library\Requests\Base\SerialNumberRequest;
use App\Models\AuctionOrderModel;
use Illuminate\Database\Eloquent\Model;

class AuctionOrderLogic extends AuctionOrderModel
{
    /**
     * paySuccess
     * @param int $id
     * @param string $payAt
     * @return int
     */
    public static function paySuccess(int $id, string $payAt): int
    {
        return self::query()->where(humpToLine(['id' => $id, 'status' => 1, 'statusPay' => 0, 'payAt' => null]))
            ->update(humpToLine([
                'status' => 2, 'payAt' => $payAt, 'statusPay' => 1
            ]));
    }

    /**
     * desc
     *
     * @param string $serialNumber
     * @return ?Model
     */
    public static function afterSaleCheck(string $serialNumber): ?Model
    {
        return self::query()->where('serial_number', $serialNumber)->where('user_id', USERID)
            ->whereNotNull('pay_at')->whereNull('refund_at')->whereIn('status_after_sale', [0, 3, 4])
            ->first([
                'id', 'seller_id', 'status', 'pay_price',
            ]);
    }

    public function userPaging(AuctionOrderPageRequest $request): array
    {
        $builder = $this->newQuery()->where('user_id', USERID);
        if (is_null($request->sortColumn)) $builder->orderBydesc('auction_order.id');
        if ($request->status === 5) {
            $builder->where('status_after_sale', 1);
            $builder->with('afterSale');
            unset($request['status']);
        } else $builder->where('status_after_sale', '<>', 1);
        return paginate(helpBuilder($builder, $request)->paginate($request->post('limit')));
    }

    public function sellerPaging(AuctionOrderPageRequest $request): array
    {
        $builder = $this->newQuery()->where('seller_id', USERID)
            ->leftJoin('auction', 'auction.id', 'auction_order.auction_id');
        if (is_null($request->sortColumn)) $builder->orderBydesc('auction_order.id');
        if ($request->status === 5) {
            $builder->where('status_after_sale', 1);
            $builder->with('afterSale');
            unset($request['status']);
        } /*else $builder->where('status_after_sale', 0);*/
        return paginate(helpBuilder($builder, $request)->paginate($request->post('limit'), ['auction_order.*', 'start_price']));
    }

    /**
     * detail
     * @param SerialNumberRequest $request
     * @return ?Model
     */
    public function auctionOrderDetail(SerialNumberRequest $request): ?Model
    {
        return self::query()->with(['logistics', 'auction', 'storeInfo'])
            ->where('auction_order.serial_number', $request->serialNumber)->first();
    }
}
